#include "TesterSharedOutputBoxImpl.h"

namespace jm4bbx { 

	TesterSharedOutputBoxImpl::TesterSharedOutputBoxImpl() 
		:/* sharedOutputs_(-1),*/ closedStreams_(0), errorHandled_(false) {
			stream_.setSharedOutputCloseListener(this);
	}


	void TesterSharedOutputBoxImpl::streamClosed() {
		if (++closedStreams_ != getSharedOutputCount()) {
			return;
		}
		else {
			closedStreams_ = 0;
		}

		BoxDataTable t;
		getDataProvider()->loadData(getDataSpecification(), &t);

		SharedOutputStreamBuffer::Buffer requiredResult;
		for (size_t i = 0; i < t.getRowCount(); ++i) {
			requiredResult.push_back(t.getLine(i));
		}

		compare(requiredResult, *stream_.getBuffer());
		stream_.reset();
	}


	void TesterSharedOutputBoxImpl::check(size_t testedRow, int& fails, const std::string& r, 
		const std::string& b) const {
			if(r != b) {
				if (!errorHandled_) {
					errorHandled_ = true;
					std::cerr	
						//<< " ------------------- " << std::endl
						<< "[" << testedRow << "]" 
						<< " >>> req >>>" << r << "<<< " << std::endl
						<< " >>> res >>>" << b << "<<< " << std::endl;
				}
				++fails;
			}
			else {
				// Vyis aj spravnych dvojic.
				//std::cerr	
				//	<< " =====" << r << "===== " << std::endl
				//	<< " =====" << b << "===== " << std::endl 
				//	<< " ------------------- " << std::endl;
			}
	}


	void TesterSharedOutputBoxImpl::compare(SharedOutputStreamBuffer::Buffer& requiredResult, SharedOutputStreamBuffer::Buffer& buffer) {
		// Zotriedenie riadkov aby som porovnaval tie ktore si prislusia.
		std::sort(requiredResult.begin(), requiredResult.end());
		std::sort(buffer.begin(), buffer.end());
		std::stringstream stream;

		// Porovnanie riadkov.
		int fails = 0;

		if (buffer.size() != requiredResult.size()) {
			std::cerr << "Pozadovany pocet riadkov vyslednej tabulky " 
				<< requiredResult.size() << " nezodpoveda realnemu poctu riadkov vyslednej tabulky " 
				<< buffer.size() << " !!!" << std::endl;
		}

		for (size_t i = 0; i < buffer.size() && i < requiredResult.size(); ++i) {
			check(i, fails, requiredResult[i], buffer[i]);
		}

		// Riadky ktore su naviac v pozadovanom vysledku.
		if (buffer.size() < requiredResult.size()) {
			for (size_t i = buffer.size(); i < requiredResult.size(); ++i) {
				check(i, fails, requiredResult[i], "");
			}
		}// Riadky ktore su naviac v testovanom vysledku.
		else if (buffer.size() > requiredResult.size()) {
			for (size_t i = requiredResult.size(); i < buffer.size(); ++i) {
				check(i, fails, "", buffer[i]);
			}
		}
		// Zhodnotenie chybovosti.
		if (fails) {
			std::cerr << "Test " << getTestName() << ": " 
				<< fails << " fails" << std::endl;
			throw "STOP";
		}
		else {
			std::cerr << "Test " << getTestName() << ": OK " 
				<< " [compared rows: " << requiredResult.size() << "]" 
				<< std::endl;
		}
	}

} // namespace jm4bbx
